package com.hopu.petshop.controller;

import com.hopu.petshop.entity.Pet;
import com.hopu.petshop.service.PetService;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * 宠物控制器
 */
@Controller
public class PetController {

    @Autowired
    private PetService petService;

    @RequestMapping("/findPetsPage")
    public String findPage(@RequestParam(value = "current",
            required = false,defaultValue = "1") Integer current,
                           Model model) throws SQLException {
        //调用PetService对象
        //执行查询，把集合存到request中
        model.addAttribute("page", petService.findPetsPage(current));
        //跳转到宠物列表页面
        return "pets";
    }

    /**
     * 根据昵称查询宠物是否存在，ajax交互
     * @ResponseBody 将方法的返回值直接以数据的方式返回
     */
    @ResponseBody
    @RequestMapping("/findPetByName")
    public String findPetByName(String name) throws SQLException {
        List<Pet> pet = petService.findPetByName(name);
        if(pet == null || pet.size() == 0){
            return "ok";
        }
        return "exists";
    }

//    @ResponseBody
//    @PostMapping("/addPet")
//    public List<Pet> addPet(@RequestBody Pet pet){
//        System.out.println(pet);
//        List<Pet> pets = Arrays.asList(
//                new Pet(1,"xx",2,"xx","x",11,1,1),
//                new Pet(2,"yy",2,"xx","x",22,2,2));
//        return pets;
//    }

    public static final String PATH = "D:\\apache-tomcat-8.5.39\\webapps\\pet-images\\";

//    @PostMapping("addPet")
//    protected String addPet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        //创建上传对象
//        ServletFileUpload upload = new ServletFileUpload();
//        //判断请求中是否有上传内容
//        if(ServletFileUpload.isMultipartContent(req)){
//            //设置上传的大小
//            upload.setFileSizeMax(10 * 1024 * 1024);
//            //获得表单的内容迭代器
//            try {
//                FileItemIterator itemIterator = upload.getItemIterator(req);
//                String name = null;
//                String age = null;
//                String gender = null;
//                String color = null;
//                String price = null;
//                String typeId = null;
//                String image = null;
//                //遍历表单内容
//                while(itemIterator.hasNext()){
//                    FileItemStream itemStream = itemIterator.next();
//                    //是否是一般的表单内容
//                    if(itemStream.isFormField()){
//                        //读取表单的值
//                        String value = Streams.asString(itemStream.openStream(),"UTF-8");
//                        //对表单的名称进行判断
//                        switch (itemStream.getFieldName()){
//                            case "name": name = value;break;
//                            case "age": age = value;break;
//                            case "gender": gender = value;break;
//                            case "color": color = value;break;
//                            case "price": price = value;break;
//                            case "typeId": typeId = value;break;
//                        }
//                    }else{
//                        //如果是文件域
//                        if("image".equals(itemStream.getFieldName())){
//                            //获得文件名
//                            image = itemStream.getName();
//                            image = System.currentTimeMillis() + FilenameUtils.getName(image);
//                            OutputStream out = new FileOutputStream(PATH + image);
//                            //实现文件保存
//                            Streams.copy(itemStream.openStream(), out, true);
//                        }
//                    }
//                }
//                try {
//                    petService.addPet(new Pet(0,name,Integer.valueOf(age),color,gender,Integer.valueOf(price),Integer.valueOf(typeId),null,image));
//                    System.out.println("添加成功！");
//                } catch (SQLException e) {
//                    e.printStackTrace();
//                }
//            } catch (FileUploadException e) {
//                e.printStackTrace();
//            }
//        }
//        return "redirect:findPetsPage";
//    }

    @PostMapping("addPet")
    protected String addPet(MultipartFile pic,Pet pet) throws SQLException, IOException {
        //获得新的文件名
        String filename = System.currentTimeMillis() + FilenameUtils.getName(pic.getOriginalFilename());
        //保存文件到磁盘上
        pic.transferTo(new File(PATH + filename));
        pet.setImage(filename);
        //添加数据库
        petService.addPet(pet);
        return "redirect:findPetsPage";
    }
}
